/*
 * @Author: axe
 * @Email: hedgehogee@sina.com
 * @Date: 2023-04-04 11:44:41
 * @Last Modified by: Axe
 * @Last Modified time: 2025-04-22 17:03:46
 */

import { createRouter, createWebHashHistory, createWebHistory, type RouteRecordRaw } from 'vue-router'

// 通过Vite的import.meta.glob()方法实现自动化导入路由
const mainRouterModules = import.meta.glob('../layout/*.vue')
const viewRouterModules = import.meta.glob('../views/**/*.vue')
const excludeFileNameRegExp = /\/component(s)?\//g

// 子路由
const childRoutes = Object.keys(viewRouterModules)
  .filter((path) => !excludeFileNameRegExp.test(path))
  .map((path) => {
    // eg.
    // @/view/example.vue  ->  ['example']
    // @/view/exampleFile/example.vue  ->  ['exampleFile', 'example']

    // @/views/home/index.vue  ->  ['home', 'index']
    // @/views/home/meeting.vue  ->  ['home', 'meeting']
    // @/views/login/index.vue  ->  ['login', 'index']
    const filePath = path.match(/\.\.\/views\/(.*)\.vue$/)![1].split('/')

    // eg.
    // ['example']  -> '/example'
    // ['home', 'index']  ->  '/home'
    // ['home', 'meeting']  ->  '/home/meeting'
    const routePath = filePath.reduce((acc, cur, idx) => {
      // 如果文件名为 index，则跳过
      if (idx === filePath.length - 1 && cur.toLowerCase() === 'index') return acc
      return `${acc}/${cur.toLowerCase()}`
    }, '')

    // 路由名
    const routeName = routePath.slice(1).replace('/', '-')

    return {
      path: routePath,
      name: routeName,
      component: viewRouterModules[path]
    }
  })

// 根路由
const rootRoutes = Object.keys(mainRouterModules).map((path) => {
  const name = path.match(/\.\.\/layout\/(.*)\.vue$/)![1].toLowerCase()
  const routePath = `/${name}`
  if (routePath === '/index') {
    return {
      path: '/',
      name,
      redirect: '/home',
      component: mainRouterModules[path],
      children: childRoutes
    }
  }

  return {
    name,
    path: routePath,
    component: mainRouterModules[path]
  }
})

const routes: Array<RouteRecordRaw> = rootRoutes

const router = createRouter({
  history: import.meta.env.MODE === 'offline' ? createWebHashHistory(import.meta.env.BASE_URL) : createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  // user auth & access control
  next()
})

export default router
